package com.eric.media;

import android.Manifest;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity
        implements MediaPlayer.OnCompletionListener,MediaPlayer.OnErrorListener ,
        MediaPlayer.OnPreparedListener,MediaPlayer.OnSeekCompleteListener{

    private MediaPlayer player;
    /**资源文件本地路径*/
    private String path;
    /**资源文件网上路径*/
    private String urlPath = "http://gdlt.sc.chinaz.com/Files/DownLoad/sound1/201706/8780.wav";
    @AfterViews
    void initData(){
        player = new MediaPlayer();
//        loadRaw();
    }

    /**
     * 装载应用程序的资源文件
     */
    void loadRaw(){
         /*
         * 判断音频是否在正在播放，如果是正在播放，
         * 就要调用reset方法进行重置，此时player会处于空闲状态，
         * 如果不进行重置的话，再调用setDataSource设置资源时，会抛出异常 IllegalStateException
         */
        if (player.isPlaying()){
//            player.release();
            player.stop();
        }
        player.reset();
//        player = MediaPlayer.create(this, R.raw.hongyanjiu);
        AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.hongyanjiu);
        try {
            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();
            player.prepare();
            player.start();
            //设置播放监听
            setListener();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载assets中的音频资源
     */
    void loadAsset(){
        /*
         * 判断音频是否在正在播放，如果是正在播放，
         * 就要调用reset方法进行重置，此时player会处于空闲状态，
         * 如果不进行重置的话，再调用setDataSource设置资源时，会抛出异常 IllegalStateException
         */
//        player.isLooping()
        if (player.isPlaying()){
//            player.release();
            player.stop();
        }
        player.reset();
        //AssetManage对象
        AssetManager am = getAssets();
        //打开指定音频文件
        try {
            AssetFileDescriptor afd = am.openFd("hongyanjiu.mp3");
            //给MediaPlayer添加资源文件
            player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            //做准备工作：装载音频  使用setDataSource()方法添加资源 必须再调用prepare()装载音频, 而后才能调用start方法开始播放
            afd.close();
            player.prepare();
            player.start();
            setListener();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     *  播放外部储存设备上的音频资源
     */
    void loadSDK(){
      /*
         * 判断音频是否在正在播放，如果是正在播放，
         * 就要调用reset方法进行重置，此时player会处于空闲状态，
         * 如果不进行重置的话，再调用setDataSource设置资源时，会抛出异常 IllegalStateException
         */
        if (player.isPlaying()){
//            player.release();
            player.stop();
        }
        player.reset();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //动态判断手机储存空间的权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == -1 ||
                    ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE ) == -1){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE},0x123);
            }else {
                try {
                    copyFileFromAssetToSDK();
                    if (TextUtils.isEmpty(path)){
                        return;
                    }
                    player.setDataSource(path);
                    player.prepare();
                    player.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            try {
                copyFileFromAssetToSDK();
                if (TextUtils.isEmpty(path)){
                    return;
                }
                player.setDataSource(path);
                player.prepare();
                player.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 播放网络资源
     */
    void loadNet(){
         /*
         * 判断音频是否在正在播放，如果是正在播放，
         * 就要调用reset方法进行重置，此时player会处于空闲状态，
         * 如果不进行重置的话，再调用setDataSource设置资源时，会抛出异常 IllegalStateException
         */
        if (player.isPlaying()){
            player.stop();
        }
        player.reset();
        Uri url =  Uri.parse(urlPath);
        try {
            player.setDataSource(this,url);
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 先把asset中资源文件copy到sdk中
     */
    public void  copyFileFromAssetToSDK(){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ){
            path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getPackageName();
        }else {
            path = Environment.getDataDirectory().getAbsolutePath() + File.separator + getPackageName();
        }

        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        //AssetManage对象
        AssetManager am = getAssets();
        try {
            AssetFileDescriptor afd = am.openFd("hongyanjiu.mp3");
            InputStream is = afd.createInputStream();
//            InputStreamReader reader  =  new InputStreamReader(afd.createInputStream());
//            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File(path,"hongyanjiu.mp3")));
            File  needFile = new File(path,"hongyanjiu.mp3");
//            if (!needFile.exists()){
//                needFile.mkdirs();
//            }
            path = needFile.getAbsolutePath();
            Log.e("音频文件路径====>", path);
            OutputStream os = new FileOutputStream(needFile);
            int hasRead = 0;
            byte[] buffer = new byte [1024];
            while ((hasRead = is.read(buffer)) != -1){
                os.write(buffer,0,hasRead);
            }
            os.flush();
            os.close();
            is.close();
            afd.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x123){
            if (grantResults[0] == 0 && grantResults[1] == 0){
                Toast.makeText(this, "已授权", Toast.LENGTH_SHORT).show();
                try {
                    copyFileFromAssetToSDK();
                    if (TextUtils.isEmpty(path)){
                        return;
                    }
                    player.setDataSource(path);
                    player.prepare();
                    player.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 设置监听
     */
    void setListener(){
        player.setOnCompletionListener(this);
        player.setOnErrorListener(this);
        player.setOnPreparedListener(this);
        player.setOnSeekCompleteListener(this);
    }

    @Click({R.id.btn_raw,R.id.btn_asset,R.id.btn_sdk,R.id.btn_Net,R.id.btn_start,R.id.btn_pause,R.id.btn_stop})
    void onClick(View view){
        switch (view.getId()){
            case R.id.btn_raw:
                loadRaw();
                break;
            case R.id.btn_asset:
                loadAsset();
                break;
            case R.id.btn_sdk:
                loadSDK();
                break;
            case R.id.btn_Net:
                loadNet();
                break;
            case R.id.btn_start:
                if (null != player){
                    player.start();
                }
                break;
            case R.id.btn_pause:
                if (null != player){
                    player.pause();
                }
                break;
            case R.id.btn_stop:
                if (null != player){
                    player.stop();
                }
                break;
        }
    }

    /**
     * 音频播放完成调用该方法
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        Toast.makeText(this, "音频播放完毕", Toast.LENGTH_SHORT).show();
    }

    /**
     * 音频播放错误调用该方法
     * @param mp
     * @param what  错误类型
     * @param extra
     * @return
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Toast.makeText(this, "音频播放发生错误", Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
     * 当方法prepare被调用触发该方法
     * @param mp
     */
    @Override
    public void onPrepared(MediaPlayer mp) {
        Toast.makeText(this, "音频播放已就绪", Toast.LENGTH_SHORT).show();
    }


    /**
     * 当调用seek方法时触发该方法
     * @param mp
     */
    @Override
    public void onSeekComplete(MediaPlayer mp) {
        Toast.makeText(this, "音频播放已seek", Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player.isPlaying()){
            player.stop();
            player.release();
        }
    }
}
